<template>
    <div class="iome-container">
        <div class="input-group">
            <div class="input-item">
                <label>样本平均值 (μ):</label>
                <input type="number" v-model.number="mean" step="0.1">
            </div>
            <div class="input-item">
                <label>测量值 (X):</label>
                <input type="number" v-model.number="measurement" step="0.1">
            </div>
            <div class="input-item">
                <label>真实值 (X₀):</label>
                <input type="number" v-model.number="trueValue" step="0.1">
            </div>
            <div class="input-item">
                <label>标准差 (σ):</label>
                <input type="number" v-model.number="stdDev" step="0.1" min="0.1">
            </div>
            <div class="input-item">
                <label>系统误差线位置 (Y):</label>
                <input type="number" v-model.number="errorLineYPosition" step="0.1" min="0" max="1">
            </div>
            <div class="input-item">
                <label>随机误差线位置 (Y):</label>
                <input type="number" v-model.number="errorLineYPosition1" step="0.1" min="0" max="1">
            </div>
            <div class="input-item">
                <label>总误差线位置 (Y):</label>
                <input type="number" v-model.number="errorLineYPosition2" step="0.1" min="0" max="1">
            </div>
            <button @click="generateExample" class="example-btn">示例数据</button>
        </div>

        <div ref="chartContainer" class="chart-container"></div>
        <div ref="confidenceChartContainer" class="chart-container"></div> <!-- 新增置信区间图表容器 -->
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect, nextTick } from 'vue'
import * as echarts from 'echarts'

// 在ref声明部分添加新参数
const mean = ref(5)
const measurement = ref(6.68)
const trueValue = ref(2)
const stdDev = ref(1)
const errorLineYPosition = ref(0.1)  // 新增：系统误差线y轴位置
const errorLineYPosition1 = ref(0.1)  // 新增：系统误差线y轴位置
const errorLineYPosition2 = ref(0.15)  // 新增：系统误差线y轴位置
const chartContainer = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null
const confidenceChartContainer = ref<HTMLElement | null>(null)
let confidenceChart: echarts.ECharts | null = null

// 生成正态分布数据
const generateNormalData = () => {
    const data: (number | number[])[] = []
    const min = mean.value - 4 * stdDev.value
    const max = mean.value + 4 * stdDev.value
    const step = (max - min) / 200  // 增加采样点数量

    for (let x = min; x <= max; x += step) {
        const exponent = -0.5 * Math.pow((x - mean.value) / stdDev.value, 2)
        const y = (1 / (stdDev.value * Math.sqrt(2 * Math.PI))) * Math.exp(exponent)
        // 原代码意图是将生成的[x, y]坐标对添加到data数组中
        // 这里推测可能是data类型定义有误，应将其类型改为(number | number[])[]
        data.push([x, y])
    }
    return data
}

// 初始化图表
onMounted(() => {
    if (chartContainer.value) {
        chart = echarts.init(chartContainer.value)
        updateChart()
    }
})

// 动态更新图表（修改watch部分）
watchEffect((onInvalidate) => {
    // 强制读取所有依赖项，确保手动修改参数图像更新
    const trigger = [mean.value, measurement.value, trueValue.value, stdDev.value, errorLineYPosition.value, errorLineYPosition1.value]
    if (chart) {
        updateChart()
    }
})

// 在updateChart函数中修改系统误差线配置
const updateChart = () => {
    const option = {
        title: {
            text: '测量误差分布示意图',
            left: 'center'
        },
        xAxis: {
            name: '值',
            min: mean.value - 4 * stdDev.value,
            max: mean.value + 4 * stdDev.value,
            axisLabel: { show: true }  // 确保显示坐标轴标签
        },
        yAxis: {
            name: '概率密度',
        },
        series: [{
            type: 'line',
            smooth: 0.4,  // 调整平滑度
            showSymbol: false,  // 禁用数据点标记
            data: generateNormalData(),
            areaStyle: {
                color: 'rgba(64, 158, 255, 0.2)'
            },
            lineStyle: {
                color: 'blue'
            },
            markLine: {
                symbol: 'none',
                data: [
                    {
                        name: '真实值',
                        xAxis: trueValue.value,
                        lineStyle: {
                            color: 'black',
                            width: 2,
                        },
                        label: {
                            show: true,
                            position: 'end',
                            distance: 1,
                            formatter: 'X₀'
                        }
                    },
                    {
                        name: '测量值',
                        xAxis: measurement.value,
                        lineStyle: {
                            color: '#000000',
                            width: 2,
                        },
                        label: {
                            show: true,
                            position: 'end',
                            distance: 1,
                            formatter: 'X'
                        }
                    },
                    {
                        name: '平均值',
                        xAxis: mean.value,
                        lineStyle: {
                            color: '#000000',
                            width: 2,
                        },
                        label: {
                            show: true,
                            position: 'end',
                            distance: 1,
                            formatter: 'μ'
                        }
                    },
                ]
            }
        },
        {
            type: 'line',
            smooth: 0.4,
            showSymbol: false,
            data: generateNormalData(),
            markLine: {
                symbol: 'arrow',
                data: [
                    [
                        {   // 起点配置
                            coord: [trueValue.value, errorLineYPosition.value],
                        },
                        {   // 终点配置
                            coord: [mean.value, errorLineYPosition.value],
                            lineStyle: {
                                color: '#F56C6C',
                                width: 2,
                                type: 'solid'
                            },
                            label: {
                                show: true,
                                position: 'middle',
                                formatter: '系统误差（β）',
                                color: '#F56C6C',
                                fontSize: 12,
                                fontWeight: 'bold'
                            }
                        }
                    ],
                    [
                        {   // 起点配置
                            coord: [measurement.value, errorLineYPosition1.value],
                        },
                        {   // 终点配置
                            coord: [mean.value, errorLineYPosition1.value],
                            lineStyle: {
                                color: 'blue',
                                width: 2,
                                type: 'solid'
                            },
                            label: {
                                show: true,
                                position: 'middle',
                                formatter: '随机误差（ε）',
                                color: 'blue',
                                fontSize: 12,
                                fontWeight: 'bold'
                            }
                        }
                    ],
                    [
                        {   // 起点配置
                            coord: [measurement.value, errorLineYPosition2.value],
                        },
                        {   // 终点配置
                            coord: [trueValue.value, errorLineYPosition2.value],
                            lineStyle: {
                                color: 'black',
                                width: 2,
                                type: 'solid'
                            },
                            label: {
                                show: true,
                                position: 'middle',
                                formatter: '总误差（α）',
                                color: 'black',
                                fontSize: 12,
                                fontWeight: 'bold'
                            }
                        }
                    ]
                ]
            }
        }],
        tooltip: {
            trigger: 'axis',
            formatter: (params: any) => {
                const x = params[0].data[0].toFixed(2)
                const y = params[0].data[1].toFixed(4)
                return `值: ${x}<br>概率密度: ${y}`
            }
        }
    }

    // 强制清除旧配置
    chart?.clear()
    chart?.setOption(option, true)
    chart?.resize()
}

// 生成示例数据
const generateExample = () => {
    mean.value = 10
    measurement.value = 12
    trueValue.value = 6
    stdDev.value = 1.2

    // 强制更新图表
    nextTick(() => {
        if (chart) {
            updateChart()
            chart.resize()  // 添加resize确保视图刷新
        }
    })
}

// 新增绘制置信区间图表的函数
const updateConfidenceChart = () => {
    const option = {
        title: {
            text: '95% 置信区间示意图',
            left: 'center'
        },
        xAxis: {
            name: '测量值',
            min: mean.value - 4 * stdDev.value,
            max: mean.value + 4 * stdDev.value
        },
        yAxis: {
            name: '出现频率'
        },
        series: [{
            type: 'line',
            smooth: 0.4,
            showSymbol: false,
            data: generateNormalData(),
            areaStyle: {
                color: 'rgba(64, 158, 255, 0.2)'
            },
            lineStyle: {
                color: 'blue'
            },

            markLine: {
                symbol: 'none',
                data: [
                    {
                        name: 'μ-2σ',
                        xAxis: mean.value - 2 * stdDev.value,
                        lineStyle: {
                            color: 'black',
                            width: 2,
                            type: 'dashed'
                        },
                        label: {
                            show: true,
                            position: 'end',
                            formatter: 'μ-2σ'
                        }
                    },
                    {
                        name: 'μ+2σ',
                        xAxis: mean.value + 2 * stdDev.value,
                        lineStyle: {
                            color: 'black',
                            width: 2,
                            type: 'dashed'
                        },
                        label: {
                            show: true,
                            position: 'end',
                            formatter: 'μ+2σ'
                        }
                    },
                    [
                        {   // 起点配置
                            coord: [mean.value - 2 * stdDev.value, errorLineYPosition2.value],
                            symbol: 'arrow'
                        },
                        {   // 终点配置
                            coord: [mean.value + 2 * stdDev.value, errorLineYPosition2.value],
                            symbol: 'arrow',
                            lineStyle: {
                                color: 'black',
                                width: 2,
                                type: 'solid'
                            },
                            label: {
                                show: true,
                                position: 'middle',
                                formatter: '95%置信区间',
                                color: 'black',
                                fontSize: 12,
                                fontWeight: 'bold'
                            }
                        }
                    ]
                ]
            }
        }]
    }

    confidenceChart?.clear()
    confidenceChart?.setOption(option, true)
    confidenceChart?.resize()
}

// 初始化时创建两个图表
onMounted(() => {
    if (chartContainer.value && confidenceChartContainer.value) {
        chart = echarts.init(chartContainer.value)
        confidenceChart = echarts.init(confidenceChartContainer.value)
        updateChart()
        updateConfidenceChart()
    }
})

// 更新时同时更新两个图表
watchEffect((onInvalidate) => {
    // 强制读取所有依赖项，确保手动修改参数图像更新
    const trigger = [mean.value, measurement.value, trueValue.value, stdDev.value, errorLineYPosition.value, errorLineYPosition1.value]
    if (chart && confidenceChart) {
        updateChart()
        updateConfidenceChart()
    }
})
</script>

<style scoped>
/* 新增样式确保两个图表有适当间距 */
.chart-container {
    width: 34%;
    /* 设置宽度为48%，留出间距 */
    height: 400px;
    display: inline-block;
    /* 使图表容器并排显示 */
    margin-right: 2%;
    /* 添加右边距 */
}

/* 最后一个图表容器不需要右边距 */
.chart-container:last-child {
    margin-right: 0;
}

.iome-container {
    padding: 20px;
    margin: 0 auto;
}

.input-group {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 15px;
    margin-bottom: 20px;
}

.input-item {
    display: flex;
    flex-direction: column;
}

input[type="number"] {
    padding: 1px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-top: 1px;
}

.example-btn {
    grid-column: span 2;
    padding: 5px;
    background: #409EFF;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;
}

.example-btn:hover {
    background: #66b1ff;
}
</style>